package com.candoit.webapps.filters;

import java.io.IOException;
import java.io.PrintWriter;

import javax.persistence.NoResultException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.candoit.webapps.pricing.bean.PricingService;
import com.candoit.webapps.pricing.model.Articulo;
import com.candoit.webapps.pricing.model.Formato;
import com.candoit.webapps.pricing.model.Linea;
import com.candoit.webapps.pricing.model.MateriaPrima;
import com.candoit.webapps.pricing.model.Medida;
import com.candoit.webapps.pricing.util.QueryUtil;

public class PriceFilter implements Filter{

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}	

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
//		String url = ((HttpServletRequest)request).getRequestURL().toString();
//		String suburl = url.substring(url.lastIndexOf('/')+1, url.length());
		String lineaP = request.getParameter("linea");
		String medidaP = request.getParameter("medida");
		String cantidadP = request.getParameter("cantidad");
		
		Double precio = 0.0;
		try {
			Articulo articulo = getArticulo(lineaP,medidaP);
			MateriaPrima mp = QueryUtil.getInstance().getMateriaByDescription("KRAFT BLANCO 100 Grs.");
			precio = PricingService.getInstance().getPrice(articulo,mp);
		} catch (Exception e) {
			precio = -1.;
		}
		

		response.setContentType("text/html;charset=utf-8");
		((HttpServletResponse)response).setHeader("Access-Control-Allow-Origin", "*");
		((HttpServletResponse)response).setHeader("Access-Control-Allow-Methods", "GET");
		((HttpServletResponse)response).setHeader("Access-Control-Allow-Headers", "Content-Type");
		((HttpServletResponse)response).setHeader("Access-Control-Max-Age", "86400");
		
		PrintWriter pr =((HttpServletResponse)response).getWriter();
		pr.print(precio);
		pr.close();
		
	}
	
	private Articulo getArticulo(String lineaP,String medidaP)throws Exception{
		Linea linea = QueryUtil.getInstance().getLineaByName(lineaP);
		Medida medida = getMedida(medidaP);
		Formato formato = QueryUtil.getInstance().getFormatoByMedidaAndLinea(medida, linea);
		return QueryUtil.getInstance().getArticulosByFormato(formato).get(0);
	}
	
	private Medida getMedida(String medidaP) throws NoResultException{
		Integer ancho, largo ,alto;
		String[] medidas = medidaP.split("x");
		ancho = Integer.parseInt(medidas[0].toString());
		largo = Integer.parseInt(medidas[1].toString());
		alto = Integer.parseInt(medidas[2].toString());
		return QueryUtil.getInstance().getMedida(ancho,largo,alto);
	}

	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
